package com.ideafactory.client.utils;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsoluteLayout;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.VideoView;

import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.views.FullVideoView;
import com.ideafactory.client.views.ImageViewAutoPlay;
import com.ideafactory.client.ybselfservice.R;
import com.lidroid.xutils.BitmapUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Code on 2016/4/18.
 */
public class ViewUtil {

    private static final String TAG = "ViewUtil";

    public static void addImageAndVideoView(final Context context,final String[] imageArray,final WindowManager wm,final LinearLayout absoluteLayout,final String playtime,final BitmapUtils bitmapUtils) {

        final  List<String> downLoads = new ArrayList<String>();
        String path = FileConstants.VIDEO_CACHE_PATH;
        final DownloadCounter counter=new DownloadCounter();
        counter.setAllCount(imageArray.length);
        counter.setCounter(imageArray.length);
         final   AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("文件下载中");

        builder.setTitle("总共"+counter.getAllCount()+"个文件，还剩"+counter.getAllCount()+"个文件");

       final AlertDialog dialog=builder.create();
        for (int i = 0; i < imageArray.length; i++) {

            int index = imageArray[i].lastIndexOf("/");
            String str = imageArray[i].substring(index + 1, imageArray[i].length());

            System.out.println("imageArray[i]------------->" + imageArray[i]);
            final    String filepath = path + str;
            downLoads.add(filepath);
            File file=new File(filepath);
            if (!file.exists()){
                NetUtils.DownLoadFile(imageArray[i], filepath, new MyCallBack<File>() {

                    @Override
                    public void onSuccess(File result) {
                        Log.e(TAG, "result.getAbsolutePath()--------->" + result.getAbsolutePath() );
                        counter.setCounter(counter.getCounter() - 1);
                        if (counter.getCounter() > 0) {
//
//                            dialog.setTitle("总共" + counter.getAllCount() + "个文件，还剩" + counter.getCounter() + "个文件");
//                            dialog.show();
                        } else {
//                            dialog.setTitle("总共" + counter.getAllCount() + "个文件，还剩" + counter.getCounter() + "个文件");
//                            dialog.dismiss();
                            Toast.makeText(context, "下载完成！", Toast.LENGTH_LONG).show();

                        }
                        Log.e(TAG, "onSuccess:-------------->"+"总共" + counter.getAllCount() + "个文件，还剩" + counter.getCounter() + "个文件" );

                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        System.out.println(filepath + "失败");
                        System.out.println("ex----->" + ex.getMessage().toString());
                    }


                });
            }else{
                counter.setCounter(counter.getCounter()-1);
            }

        }

        String[] imageBitmap = new String[downLoads.size()];
        downLoads.toArray(imageBitmap);

        FrameLayout frameLayout = addImageAndVideo(context, imageBitmap, wm, absoluteLayout,playtime,bitmapUtils);
        absoluteLayout.addView(frameLayout);
    }

    protected void dialog(Context context,int all,int last) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("下载文件中");

        builder.setTitle("总共"+all+"个文件，还剩"+last+"个文件");

        builder.create().show();
    }

    public static FrameLayout addImageAndVideo(Context context,final String[] imageArray, WindowManager wm,final LinearLayout absoluteLayout,String playtime,BitmapUtils bitmapUtils) {

        AbsoluteLayout.LayoutParams layoutParams = new AbsoluteLayout.LayoutParams(absoluteLayout.getWidth(), absoluteLayout.getHeight(), absoluteLayout.getLeft(), absoluteLayout.getTop());
       final FrameLayout linearLayout = new FrameLayout(context);
        if (imageArray.length==0){
            absoluteLayout.setBackgroundResource(R.mipmap.mainbg_moren);
        }
        linearLayout.setLayoutParams(layoutParams);

        //创建的两个图片和视频播放的view
       final ImageView imageView = new ImageView(context);
        imageView.setVisibility(View.INVISIBLE);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        final VideoView videoView = new VideoView(context);
        videoView.setVisibility(View.INVISIBLE);

        for (int i = 0; i < imageArray.length; i++) {
            String path = imageArray[i];
            Log.e(TAG, "addImageAndVideo---------->"+imageArray[i]);
            boolean isVideo = false;
            if (FileUtils.isVideo(path)) {
                isVideo = true;
            }
            if (i == 0) {
                if (isVideo) {
                    linearLayout.setBackgroundColor(Color.parseColor("#000000"));
                    final File file = new File(path);
                    if (file.exists()) {
                        videoView.setVisibility(View.VISIBLE);
                        videoView.setVideoPath(file.toString());
                        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                videoView.start();

                            }
                        });
                        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                            @Override
                            public boolean onError(MediaPlayer mp, int what, int extra) {
                                if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
                                } else if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
                                } else if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
                                }

                                return true;
                            }
                        });

                    }
                } else {
//                    x.image().bind(imageView,path);
                    bitmapUtils.display(imageView,path);
                    imageView.setVisibility(View.VISIBLE);

                }
            }
        }
        if (imageArray.length > 1) {
            // 添加自动播放
            Double playTime = Double.parseDouble(playtime);
            final ImageViewAutoPlay imageViewAutoPlay = new ImageViewAutoPlay(imageArray, imageView, videoView, playTime.intValue() * 1000,linearLayout,bitmapUtils);
            final Handler handler = new Handler();
            if (imageView.getVisibility() == View.VISIBLE) {
                handler.postDelayed(imageViewAutoPlay, imageViewAutoPlay.playTime);
            }
            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mp.start();
                }
            });
            videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mPlayer) {

                    if (imageArray.length == 1) {
                        videoView.setVideoPath(imageArray[0]);
                        videoView.start();
                    } else {
//
//                        imageView.setBackgroundColor(Color.parseColor("#000000"));
//                        handler.postDelayed()
                        handler.postDelayed(imageViewAutoPlay, 0);
                    }
                }
            });
            videoView.requestFocus();

        } else {
            if (videoView.getVisibility() == View.VISIBLE) {

                videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.start();

                    }
                });
                videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mPlayer) {

                        videoView.setVideoPath(imageArray[0]);
                        videoView.start();
                    }
                });
                videoView.requestFocus();
            }
        }
        FrameLayout.LayoutParams logoViewParams = new FrameLayout.LayoutParams(absoluteLayout.getWidth(), absoluteLayout.getHeight());
        logoViewParams.gravity = Gravity.CENTER;
        linearLayout.addView(videoView, logoViewParams);
        linearLayout.addView(imageView, logoViewParams);

        return linearLayout;
    }

    public static Bitmap readBitmapAutoSize(String filePath, int outWidth, int outHeight) {
        // outWidth和outHeight是目标图片的最大宽度和高度，用作限制
        BitmapFactory.Options options;

        Bitmap bitmap = null;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                options = setBitmapOption(filePath, outWidth, outHeight);
                bitmap = BitmapFactory.decodeFile(filePath, options);
                return bitmap;
            }
        } catch (OutOfMemoryError error) {
            if (bitmap != null) {
                bitmap.recycle();
            }
        }
        return null;
    }

    private static BitmapFactory.Options setBitmapOption(String file,
                                                         int width, int height) {
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inJustDecodeBounds = true;
        // 设置只是解码图片的边距，此操作目的是度量图片的实际宽度和高度
        BitmapFactory.decodeFile(file, opt);

        int outWidth = opt.outWidth; // 获得图片的实际高和宽
        int outHeight = opt.outHeight;
        opt.inDither = false;
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        // 设置加载图片的颜色数为16bit，默认是RGB_8888，表示24bit颜色和透明通道，但一般用不上
        opt.inSampleSize = 1;
        // 设置缩放比,1表示原比例，2表示原来的四分之一....
        // 计算缩放比
        if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0) {
            int sampleSize = (outWidth / width + outHeight / height) / 2;
            opt.inSampleSize = sampleSize;
        }
        opt.inJustDecodeBounds = false;// 最后把标志复原
        return opt;
    }
}
